package com.iplant.mes.controller.sfc;

import com.iplant.base.po.Pagination;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.basic.controller.BasicController;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.mes.service.SFCFrockBindService;
import com.iplant.mes.service.SFCService;
import com.iplant.mes.service.po.sfc.SFCTaskIPT;
import com.iplant.mes.service.po.sfc.SFCTaskReport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 报工单控制器
 *
 * @author YouWang·Peng
 * 2023-8-30 11:26:33
 */
@RestController
@RequestMapping("/api/SFCTaskReport")
public class SFCTaskReportController extends BasicController<SFCTaskReport> {
    private static final Logger logger = LoggerFactory.getLogger(SFCTaskReportController.class);

    public SFCTaskReportController() {
        super(SFCTaskReport.class);
    }

    @Autowired
    SFCService mSFCService;

    @Autowired
    SFCFrockBindService mSFCFrockBindService;

    /**
     * 查询待报工任务集合
     */
    @GetMapping("/QueryReportTaskIPIList")
    public Object QueryReportTaskIPIList(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            Map<String, Object> wParams = GetParamsMap(request);

            ServiceResult<List<SFCTaskIPT>> wServiceResult = mSFCService.SFC_QueryReportTaskIPIList(wLoginUser,
                    wParams);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 手动报工
     */
    @PostMapping("/HandReport")
    public Object HandReport(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            List<SFCTaskIPT> wSFCTaskIPTList = CloneTool.CloneArray(wParam.get("data"), SFCTaskIPT.class);
            if (wSFCTaskIPTList == null || wSFCTaskIPTList.size() == 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }
            List<Integer> wRoutePartPointIDList =
                    wSFCTaskIPTList.stream().map(p -> p.RoutePartPointID).distinct().collect(Collectors.toList());
            if (wRoutePartPointIDList.size() > 1) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_HandReport(wLoginUser, wSFCTaskIPTList);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 数量报工
     */
    @PostMapping("/NumberReport")
    public Object NumberReport(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            SFCTaskReport wSFCTaskReport = CloneTool.Clone(wParam.get("data"), SFCTaskReport.class);
            if (wSFCTaskReport == null || wSFCTaskReport.ActNum <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_NumberReport(wLoginUser, wSFCTaskReport);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 查询待交接报工单列表
     */
    @GetMapping("/QueryToConfirmList")
    public Object QueryToHandList(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            Map<String, Object> wParams = GetParamsMap(request);
            Pagination wPagination = GetPagination(request);

            ServiceResult<List<SFCTaskReport>> wServiceResult = mSFCService.SFC_QueryToConfirmList(wLoginUser,
                    wParams, wPagination);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, wPagination.getTotalPage());
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 报工单确认
     */
    @PostMapping("/Confirm")
    public Object Confirm(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            SFCTaskReport wSFCTaskReport = CloneTool.Clone(wParam.get("data"), SFCTaskReport.class);
            if (wSFCTaskReport == null || wSFCTaskReport.ID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCService.SFC_TaskReportConfirm(wLoginUser, wSFCTaskReport);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString());
        }
        return wResult;
    }

    /**
     * 删除报工单
     */
    @Override
    @PostMapping("/Delete")
    public Object Delete(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            SFCTaskReport wSFCTaskReport = CloneTool.Clone(wParam.get("data"), SFCTaskReport.class);
            if (wSFCTaskReport == null || wSFCTaskReport.ID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCFrockBindService.SFC_DeleteTaskReport(wLoginUser,
                    wSFCTaskReport);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 查询统计数据
     */
    @GetMapping("/QueryStatistics")
    public Object QueryStatistics(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            // 获取参数
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));
            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));
            int wReporterID = StringUtils.parseInt(request.getParameter("ReporterID"));
            String wOrderNo = StringUtils.parseString(request.getParameter("OrderNo"));
            int wProductID = StringUtils.parseInt(request.getParameter("ProductID"));
            int wStationID = StringUtils.parseInt(request.getParameter("StationID"));

            if (wReporterID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "报工人必选!");
            }
            if (wStationID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, "工位必选!");
            }

            ServiceResult<List<SFCTaskReport>> wServiceResult =
                    mSFCFrockBindService.SFC_QueryStatistics(wLoginUser,
                            wStartTime, wEndTime, wReporterID, wOrderNo, wProductID, wStationID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.Result, null);
                for (String wKey : wServiceResult.CustomResult.keySet()) {
                    SetResult(wResult, wKey, wServiceResult.CustomResult.get(wKey));
                }
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }

    /**
     * 通过报工单更新进度
     */
    @GetMapping("/UpdateProgressByReportTask")
    public Object UpdateProgressByReportTask(HttpServletRequest request) {
        Object wResult = new Object();
        try {
            BMSEmployee wLoginUser = GetSession(request);

            int wTaskReportID = StringUtils.parseInt(request.getParameter("TaskReportID"));
            if (wTaskReportID <= 0) {
                return GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
            }

            ServiceResult<Integer> wServiceResult = mSFCFrockBindService.SFC_UpdateProgressByReportTask(wLoginUser,
                    wTaskReportID);

            if (StringUtils.isEmpty(wServiceResult.FaultCode)) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.FaultCode);
            }
        } catch (Exception ex) {
            logger.error(ex.toString());
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.toString(), null, null);
        }
        return wResult;
    }
}
